package com.wanji.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ThreadPoolConfig {


    /**
     * 创建一个用于计算任务的线程池
     *
     * @return ExecutorService 一个用于执行计算任务的线程池实例
     */
    @Bean
    public ExecutorService calculationExecutor() {
        // 获取可用处理器数量作为核心线程池大小
        int corePoolSize = Runtime.getRuntime().availableProcessors();

        // 创建线程池任务执行器实例
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        // 设置核心线程池大小
        executor.setCorePoolSize(corePoolSize);
        // 设置最大线程池大小为核心线程池大小的两倍
        executor.setMaxPoolSize(corePoolSize * 2);
        // 设置线程池的队列容量
        executor.setQueueCapacity(corePoolSize * 1000);
        // 设置线程存活时间
        executor.setKeepAliveSeconds(60);

        // 设置线程工厂，为线程池中的线程命名
        executor.setThreadFactory(new CustomizableThreadFactory("my-task-pool-"));

        // 设置拒绝执行策略，由调用线程自己执行被拒绝的任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        // 设置线程池在关闭时等待所有任务完成
        executor.setWaitForTasksToCompleteOnShutdown(true);

        // 初始化线程池
        executor.initialize();

        // 返回线程池实例
        return executor.getThreadPoolExecutor();
    }

}